package com.otp.service.impl;

import com.otp.pojo.entity.*;
import com.otp.exception.BusinessException;
import com.otp.repository.CheckInRepository;
import com.otp.repository.CourseJoinRepository;
import com.otp.repository.CourseRepository;
import com.otp.repository.UserRepository;
import com.otp.pojo.request.checkin.CheckInCreateRequest;
import com.otp.service.CheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CheckInServiceImpl implements CheckInService {

    @Autowired
    private CheckInRepository checkInRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private CourseJoinRepository courseJoinRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public CheckIn create(CheckInCreateRequest request) {
        courseRepository.findById(request.getCourseId())
                .orElseThrow(() -> new BusinessException("课程不存在"));

        CourseJoin courseJoin = courseJoinRepository.findByCourseIdAndStudentId(request.getCourseId(), request.getStudentId());
        if (courseJoin == null || !"APPROVED".equals(courseJoin.getStatus())) {
            throw new BusinessException("未加入该课程或加入未通过");
        }

        CheckIn checkIn = new CheckIn();
        checkIn.setCourseId(request.getCourseId());
        checkIn.setStudentId(request.getStudentId());
        return checkInRepository.save(checkIn);
    }

    @Override
    public List<CheckIn> listByCourseId(Long courseId) {
        courseRepository.findById(courseId)
                .orElseThrow(() -> new BusinessException("课程不存在"));
        return checkInRepository.findByCourseId(courseId);
    }

    @Override
    public List<CheckIn> listByStudentId(Long studentId) {
        userRepository.findById(studentId)
                .orElseThrow(() -> new BusinessException("学生不存在"));
        return checkInRepository.findByStudentId(studentId);
    }

    @Override
    public void delete(Long id) {
        CheckIn checkIn = checkInRepository.findById(id)
                .orElseThrow(() -> new BusinessException("签到记录不存在"));
        checkInRepository.delete(checkIn);
    }

    @Override
    public List<CheckInStats> getStatsByCourse(Long courseId) {
        courseRepository.findById(courseId)
                .orElseThrow(() -> new BusinessException("课程不存在"));

        // 获取课程的所有学生
        List<CourseJoin> courseJoins = courseJoinRepository.findByCourseId(courseId)
                .stream()
                .filter(join -> "APPROVED".equals(join.getStatus()))
                .toList();

        List<CheckInStats> stats = new ArrayList<>();
        // 假设总课次为固定值（可扩展为动态计算）
        long totalSessions = 10; // 假设每门课10次课

        for (CourseJoin join : courseJoins) {
            Long studentId = join.getStudentId();
            userRepository.findById(studentId)
                    .orElseThrow(() -> new BusinessException("学生不存在"));

            // 获取学生在该课程的签到记录
            List<CheckIn> checkIns = checkInRepository.findByCourseIdAndStudentId(courseId, studentId);
            long totalCheckIns = checkIns.size();
            double checkInRate = (double) totalCheckIns / totalSessions * 100;

            CheckInStats stat = new CheckInStats();
            stat.setCourseId(courseId);
            stat.setStudentId(studentId);
            stat.setTotalCheckIns(totalCheckIns);
            stat.setTotalSessions(totalSessions);
            stat.setCheckInRate(checkInRate);
            stats.add(stat);
        }

        return stats;
    }

    @Override
    public List<CheckInStats> getStatsByStudent(Long studentId) {
        userRepository.findById(studentId)
                .orElseThrow(() -> new BusinessException("学生不存在"));

        // 获取学生加入的所有课程
        List<CourseJoin> courseJoins = courseJoinRepository.findByStudentId(studentId)
                .stream()
                .filter(join -> "APPROVED".equals(join.getStatus()))
                .toList();

        List<CheckInStats> stats = new ArrayList<>();
        long totalSessions = 10; // 假设每门课10次课

        for (CourseJoin join : courseJoins) {
            Long courseId = join.getCourseId();
            courseRepository.findById(courseId)
                    .orElseThrow(() -> new BusinessException("课程不存在"));

            // 获取学生在该课程的签到记录
            List<CheckIn> checkIns = checkInRepository.findByCourseIdAndStudentId(courseId, studentId);
            long totalCheckIns = checkIns.size();
            double checkInRate = (double) totalCheckIns / totalSessions * 100;

            CheckInStats stat = new CheckInStats();
            stat.setCourseId(courseId);
            stat.setStudentId(studentId);
            stat.setTotalCheckIns(totalCheckIns);
            stat.setTotalSessions(totalSessions);
            stat.setCheckInRate(checkInRate);
            stats.add(stat);
        }

        return stats;
    }
}